package com.jk.springbootes.config;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;


/**
 * @author 赵优秀
 * @version 1.0.0
 * @ClassName EsConfig.java
 * @Description TODO
 * @createTime 2021年08月29日 19:03:00
 */
@Configuration
public class EsConfig {
    private  Logger  logger=LoggerFactory.getLogger(EsConfig.class);
   //ip
    @Value("${elasticsearch.ip}")
    private  String ip;
    //第一个服务
    @Value("${elasticsearch.firstPort}")
    private  String firstPort;
    //第二个服务
    @Value("${elasticsearch.secondPort}")
    private String secondPort;
    //第三个服务
    @Value("${elasticsearch.thirdPort}")
    private String thirdPort;
    //服务名
    @Value("${elasticsearch.clusterName}")
    private String clusterName;

    @Bean
    public TransportClient getTransportClient() throws UnknownHostException {
        logger.info("es初始化。。。。。。");
        logger.info("连接点1的ip是{}，端口是{}，集群名字是{}",ip,firstPort,clusterName);
        logger.info("连接点2的ip是{}，端口是{}，集群名字是{}",ip,secondPort,clusterName);
        logger.info("连接点3的ip是{}，端口是{}，集群名字是{}",ip,thirdPort,clusterName);
        TransportClient  transportClient=null;
        try {
            Settings settings=Settings.builder()
                    .put("cluster.name",clusterName)
                    .put("client.transport.sniff",true)
                    .build();
            transportClient=new PreBuiltTransportClient(settings);
            TransportAddress transportAddress=new TransportAddress(InetAddress.getByName(ip),Integer.parseInt(firstPort));
            TransportAddress secondAddress = new TransportAddress(InetAddress.getByName(ip),Integer.parseInt(secondPort));
            TransportAddress thirdAddress = new TransportAddress(InetAddress.getByName(ip),Integer.parseInt(thirdPort));
            transportClient.addTransportAddress(transportAddress);
            transportClient.addTransportAddress(secondAddress);
            transportClient.addTransportAddress(thirdAddress);
            logger.info("初始化完成");
        }catch (Exception e){
            e.printStackTrace();
            logger.info("失败了");
        }
        return transportClient;
    }
}
